# -*- coding: utf-8 -*-
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,time
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "华安顺意人生百种重疾保险"

    # 生产产品数据
    def genProductInfo(self):
        plan = {

            "planA": {
                "year": [str(i) for i in range(0, 50)],
                "gender": ["M", "F"],
                "socialSec": ["Y"],
                "money": ["100000"],
                "expire": ["1年"],
                "plan": ["基础款"]
            },
            "planB": {
                "year": [str(i) for i in range(0, 50)],
                "gender": ["M", "F"],
                "socialSec": ["Y"],
                "money": ["200000"],
                "expire": ["1年"],
                "plan": ["经济款"]
            },
            "planC": {
                "year": [str(i) for i in range(0, 50)],
                "gender": ["M", "F"],
                "socialSec": ["Y"],
                "money": ["300000"],
                "expire": ["1年"],
                "plan": ["优选款"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["socialSec"], plan[k]["money"],
                             plan[k]["expire"], plan[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], v[4], v[5]
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4], v[5]
                    )
                )

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["plan"] == "基础款":

            planId = "d59990d5-e30b-4f20-aece-98ab1c0d2b41"

        elif dt["plan"] == "经济款":

            planId = "2f0f4b44-4acc-43f5-9331-16fabaa482b2"

        else:
            planId = "9e70fca8-25ad-42a5-b5f2-c4d4b2183536"


        data = {
            "requestData": {"productId": "1226_syrs", "isMulti": "1", "issueChannel": "1",
                            "list": [{"cInsrncCde": "1200009", "nSelectFlag": "1", "nPrm": "90", "nAmt": ""+dt["money"][::5]+"万"}],
                            "productPlanId": planId, "securityPeriod": "Y#1",
                            "securityBirthday": "{year}-01-01".format(year = str(2020-int(dt["year"]))), "securityBgnTm": "2020-02-04"}
        }

        payload = urlencode(data).replace("+", "")


        try:
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "交易成功" in r.text:

                price = Helper.decimalParse(r.json()["premium"])

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )

            else:

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                self.mysql.updateTask( data )
                print("/*产品价格更新失败:%d*/"%dt["id"])

        except:

            pass


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

